<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;

class LoginController extends Controller {


    public function index(Request $request){
        if (auth()->guard('web')->check()) {
            return redirect(route('home.index.index'));
        }
        $username = $request->cookie('username');
        $mobile = $request->cookie('mobile');
        return view('home.login',compact('username','mobile'));
    }

    public function register(Request $request){
        try {
            $data = $request->all();
            $data['password'] = '123456';
            $user = User::where('mobile',$data['mobile'])->first();
            if($user){
                $credentials = [
                    'mobile' => $data['mobile'],
                    'password' => $data['password'],
                ];
                auth('web')->attempt($credentials);
            }else{
                //注册
                $data['password'] = bcrypt($data['password']);
                $user = User::create($data);
                auth('web')->login($user);
            }
            Cookie::queue('username', $data['username']);
            Cookie::queue('mobile', $data['mobile']);
            return $this->returnJson(0, null, '登录成功，页面即将跳转...');
        } catch (\Throwable $e) {
            return $this->returnJson(1, null, '登录失败，请联系相关人员');
        }
    }


    public function logout(Request $request)
    {
        try {
            auth('web')->logout();
            $request->session()->regenerate();
            return redirect(route('home.index.index'));
        } catch (\Exception $e) {
            return redirect(route('home.index.index'));
        }
    }


}
